package com.ruhua.java.api.cms;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.ruhua.java.core.interceptors.ScopeLevel;
import com.ruhua.java.dao.Admin;
import com.ruhua.java.exception.TrowException;
import com.ruhua.java.repository.ImageRepository;
import com.ruhua.java.service.AdminService;
import com.ruhua.java.service.TokenService;
import com.ruhua.java.vo.AdminVO;
import com.ruhua.java.vo.ResVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/cms")
public class AdminController {

    @Autowired
    TokenService tokenService;

    @Autowired
    AdminService adminService;

    @Autowired
    ImageRepository imageRepository;




    @PostMapping("/admin/edit_psw")
    @ScopeLevel(10)
    public ResVO<String> edit_psw(@RequestBody Map<String,Object> person) {
        String old = person.get("old_psw").toString();
        String psw = person.get("new_psw").toString();
        String psw2 = person.get("password2").toString();
        if (psw == null || psw.length()<6 || old == null || old.length()<6) {
            throw new TrowException("密码不能少于6位");
        }
        if (!psw.equals(psw2)) {
            throw new TrowException("二次新密码不相同");
        }
        tokenService.editPsw(psw,old);
        return ResVO.go();
    }


    @PostMapping("/login")
    public ResVO<Map> CmsLogin(@RequestBody Map<String,Object> person){
        String username = person.get("username").toString();
        String psw = person.get("psw").toString();
        if (username == null || username.length()<1 || psw == null || psw.length()<6) {
            throw new TrowException("密码不能少于6位");
        }
        Map<String, String> token=tokenService.CmsToken(username,psw);
        return ResVO.go(token);
    }

    @GetMapping("/admin/get_all_admin")
    public ResVO<List> get_all_admin(){
        Mapper mapper = DozerBeanMapperBuilder.buildDefault();List<Admin> list=adminService.findAll();
        List<AdminVO> vos = new ArrayList<>();  list.forEach(s->{
            AdminVO vo = mapper.map(s,AdminVO.class);
            vos.add(vo);
        });
        return ResVO.go(vos);
    }

    @PostMapping("/admin/add_admin")
    public ResVO<String> add_admin(@RequestBody Map<String,Object> person){
        adminService.addAdmin(person);
        return ResVO.go();
    }

    @DeleteMapping("/admin/del_admin")
    public ResVO<String> del_admin(@RequestParam Long id){
        adminService.delItem(id);
        return ResVO.go();
    }

}
